<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 
 */
class Lifebalanz extends CI_Controller {

	private $token = null;  	// user token
	private $upload_path;		// data file upload dir
	public  $tid = null;		// user tid
	public  $date = null;		// date of data
	public  $email = null;		// email of data

	/**********data handle attribute**************/
	public 	$db; 					// db handler
	// private $tid   	= null; 		// ower user id
	// private $token	= null; 		// token
	private $qquptable	= null; 		// qq upload temp table
	private $file 	= null; 		// file save 
	public  $error 	= array();		// store save error, if there is a error, do not delete the file
	public 	$qqupload_update_users = array(); // new data , set update on if user join qqhealth


	/**
	 * construc method
	 * function: initailize and verify user token before action
	 */
	public function __construct(){
		parent::__construct();
		$this->load->helper("common");

		// data file save dir
		
		// need to be a post request
		if(!(strtolower($_SERVER['REQUEST_METHOD']) == 'post') ){
			json_return(false,'need to be a post request');
		}

		$this->token = $this->input->post('token');

		// $this->tid    = $this->input->post('id');
		// $this->date  = $this->input->post('date');

		if(!$this->token ) json_return(false,'token post request');
		
		// // set test token
		// $this->token = 'd5dca16ad78a8671c776f73902a20f29';

		$this->upload_path = $this->config->item('upload_path');

		/************************************************************
		/******************token check ******************************
		/************************************************************/
		// 1. check token from local databas
		if($info = $this->_checkTokenFromDb()){
			$this->token = $info['token'];
			$this->tid = $info['tid'];

		}elseif ($info = $this->_checkTokenFromPriveteApi() ) {
		// 2. check token from private api and save user to local database
			$this->_saveUser();
		}else{
		// 3.  not a user, no access allow
			json_return(false,'not a user, no access allow');
		}
		/************************************************************/
		/*********************end************************************/
		/************************************************************/



		/********************datahandle setting*********************************/
		$this->load->model('user_data');
		$this->db = $this->user_data->db;

	}
	

	
	/**
	 * [getdata API]
	 * @param  $_POST[date] [the date search for. ]
	 *                        formate:
	 *                        1. week 	=>	number      (the week in a year)
	 *                        2. day 	=>	number		(the day in a year)
	 *                        3. month 	=>	number      (the month in a year)
	 * @param  $_POST[unit] [
	 *                        unit selection:
	 *                        	week 		(suggest)
	 *                       	day 		
	 *                       	month
	 *                      ]
	 * @return [string]     [echo json data]
	 */
	public function getdata(){
		
		$date 	= $this->input->post('date');
		// $id 	= $this->input->post('id');
		$unit 	= $this->input->post('unit');

		$unit_option = array('week','day','month','year','all');

		if($unit != 'all' && !$date){
			json_return(false,'request POST date');
		}
		$unit = $unit ? $unit : 'week';
		$unit = strtolower($unit);
		// not a valid unit
		if(!in_array($unit,$unit_option)){
			json_return(false,'please post a valid request unit');
		}

		// get cache
		$key = md5($this->tid.$date.$unit);
		if($this->config->item('cache_on') &&  $data = cache_get($key)){
			$data = jsonObj_to_array(json_decode($data));
		}else{
			$this->load->model('user_data');
			$array = array('tid'=>$this->tid,'date'=>$date);
			$data  = $this->user_data->getUserData($array,$unit);
			if($this->config->item('cache_on')){
				cache_set($key,json_encode($data),10);
			}
		}

		// var_dump($this->user_data->db->last_query());
		// var_dump($data);die;
		if(!empty($data['data']) && is_array($data['data'])){
			// echo $this->upload_path . 'get.json';die;
			// $r = file_put_contents($this->upload_path . '123/get.json', json_encode($data));
			// var_dump($r);die;
			$data['success'] = true;
			echo json_encode($data);
			exit;
		}else{
			// no data
			json_return(false,'no data');
		}
	}

	/**
	 * [getinfos]
	 * @param  $_POST[token] 
	 * @return [json] [description]
	 */
	public function getinfo(){
		// get cache
		// cache method
		// $key = md5("get_info_".$this->tid);
		// if($this->config->item('cache_on') && $infos = cache_get($key)){
		// 	$infos = jsonObj_to_array(json_decode($infos));
		// }else{
		// 	$this->load->model('user_infos');
		// 	$infos = $this->user_infos->getUserInfos($this->tid);
		// 	cache_set($key,json_encode($infos));
		// }

		// no cache
		$this->load->model('user_infos');
		$infos = $this->user_infos->getUserInfos($this->tid);
		if($infos){
			$infos['success'] = true;
			
			echo json_encode($infos);
			
			exit;
		}else{
			json_return(false,'no infos');
		}
	}

	public function getinfolastupdatemark(){
		$this->load->model('user_infos');
		$infos = $this->user_infos->db->select('lastupdatemark')->from("user_infos")->where(array('tid'=>$this->tid))->get()->row_array();
		
		$m = $infos ? $infos['lastupdatemark'] : 0;
		$mark = array(
			"lastupdatemark"=>$m
			);
		json_return(true,$mark);
	}

	/**
	* save data API 
	* @access	public
	* @param	$_POST['token']
	* @param	$_FILES['filedata']
	* @return	void
	*/
	public function save()
	{	
		if(!is_dir($this->upload_path)){
			mkdir($this->upload_path,0777,true);
		}
		// var_dump($this->upload_path);
		if(!is_writeable($this->upload_path)){
			json_return(false,'upload path is not writeable!');
		}

		// // date formate verify
		// if(!preg_match('/^\d{4}-\d{2}-\d{2}/i', $this->date)){
		// 	json_return(false,'invalid date to save');
		// }
		if(!isset($_FILES['filedata'])){
			json_return(false,'no upload file');
		}

		// if(!is_writeable($this->upload_path)){
		// 	json_return(false,'upload path is not writeable!');
		// }

		// die;
		// save post zip file
		$config['upload_path'] = $this->upload_path;	// file upload path
		$config['allowed_types'] = 'zip|json';			// allow file type
		$config['overwrite'] = true;					// overwrite if the same filename
		$config['max_size'] = '500';					// max_file_size  500K
		// save file name - formate : id_date.zip
		$config['file_name'] = $this->tid . '@##@' . $this->token . '.zip';

		$this->load->library('upload',$config);
		// var_dump($this->upload);
		if($this->upload->do_upload('filedata')){
			if((int)$this->input->post('update') == 1){
				$info = $this->upload->data();
				gearman_client(serialize($info),'data_bg_handle');

				// load url functions
				// $this->load->helper('url');
				// $url_string = site_url();
				// // echo $url_string;
				// preg_match('/((https|http):\/\/.*)\/.*$/iU',$url_string,$match);
				// if(!$match){
				// 	return;
				// }
				// $url = $match[1];
				// // handle data immediately
				// $info = $this->upload->data();
				// $info = array('info'=>$info);
				// $rs = post($url . "/datahandle",$info);
			}else{
				gearman_client('auto','data_bg_handle');

			}

			// upload success
			json_return(true,'save data success!');
		}else{
			json_return(false,'faild to save');

		}

	}



	/**
	 * [getqqupload set on or off qq upload func]
	 * $_POST[access_token]
	 * $_POST[is_join]
	 * $_POST[lastupdatemark]
	 * @return [json] [description]
	 */
	public function setqqupload(){
		$access_token = $this->input->post('access_token') ? $this->input->post('access_token') : '';
		$is_join = $this->input->post('is_join')  ? ($this->input->post('is_join') == 1 ? 1 : 0) : 0;
		$lastupdatemark = 
		// check openid
		$openid = get_open_id($access_token);

		if(!$openid ){
			json_return(false,'invalid access_token');
		}


		$data = array(
			'access_token' 	=> $access_token,
			'is_join' 		=> $is_join,
			'status'		=> 1,
			);

		if( isset($_POST['lastupdatemark_step'])){
			$data['lastupdatemark_step'] = $this->input->post('lastupdatemark_step') ? (int)$this->input->post('lastupdatemark_step') : 0;
			$data['status_step'] = 1;
		}
		
		if( isset($_POST['lastupdatemark_sleep'])){
			$data['lastupdatemark_sleep'] = $this->input->post('lastupdatemark_sleep') ? (int)$this->input->post('lastupdatemark_sleep') : 0;
			$data['status_sleep'] = 1;
		}

		$where = array('tid'=>$this->tid);
		$this->load->model('user_qqhealth_api');
		$db = $this->user_qqhealth_api->db;
		$result = $db->select("tid")->from("user_qqhealth_api")->where($where)->get()->row_array();
		// var_dump($db->last_query());
		// var_dump($db->affected_rows());die;
		if($db->affected_rows()){
			// update
			$db->where("tid",$this->tid);
			
			if($db->update("user_qqhealth_api",$data)){
				json_return(true,'setting successfully');
			}else{
				json_return(false,'setting faild');
			}
		}else{
			$result = $db->select("access_token")->from("user_qqhealth_api")->where(array('access_token'=>$access_token))->get()->row_array();
			// duplicate access_token
			if($db->affected_rows()){
				json_return(false,'duplicate access_token not allow!');
			}
			// insert
			$data['tid'] = $this->tid;
			// create a temp_table_id only when creating new qqhealth user
			$temp_table_id = mt_rand(1,$this->config->item('qq_temp_tables_num'));
			$data['temp_table_id'] = $temp_table_id;

			if($db->insert('user_qqhealth_api',$data)){
				json_return(true,'setting successfully');
			}else{
				json_return(false,'setting faild');
			}
		}
	}

	/**
	 * get user lastupdatemark time
	 * @return [type] [description]
	 */
	public function lastupdatemark(){
		$where = array('tid'=>$this->tid);
		$this->load->model('user_qqhealth_api');
		$db = $this->user_qqhealth_api->db;
		$result = $db->select("tid,lastupdatemark")->from("user_qqhealth_api")->where($where)->get()->row_array();
		if($result){
			json_return(true,array('lastupdatemark'=>$result['lastupdatemark']));
		}

		json_return(false,"no data");
	}

	/**
	 * [getqqupload description]
	 * @return [type] [description]
	 */
	public function getqqupload(){
		$where = array('tid'=>$this->tid);
		$this->load->model('user_qqhealth_api');
		$db = $this->user_qqhealth_api->db;
		$result = $db->select("tid,is_join")->from("user_qqhealth_api")->where($where)->get()->row_array();

		if(!$result || $result['is_join'] != 1){
			json_return(true,array('is_join'=>false));
		}

			json_return(true,array('is_join'=>true));


	}

	/**
	 * [getupdates  :  firststamp  , laststamp]
	 * @return [type] [description]
	 */
	public function getupdates(){
		// get cache
		// $key = md5("getupdates_".$this->tid);
		// if( $this->config->item('cache_on') && $result = cache_get($key)){
		// 	$result = jsonObj_to_array(json_decode($result));
		// }else{
		// 	$this->load->model('user_data');
		// 	$db = $this->user_data->db;
		// 	$result = $db->select("lastupdate")->from("user_data")->where(array("tid"=>$this->tid))->order_by("lastupdate","desc")->limit(1)->get()->row_array();
		// 	cache_set($key,json_encode($result));
		// }
		

		$this->load->model('user_data');
		$db = $this->user_data->db;
		$result_last  = $db->select("lastupdate")->from("user_data")->where(array("tid"=>$this->tid))->order_by("date","desc")->order_by("lastupdate","desc")->limit(1)->get()->row_array();
		$result_first = $db->select("lastupdate")->from("user_data")->where(array("tid"=>$this->tid))->order_by("date","asc")->order_by("lastupdate","asc")->limit(1)->get()->row_array();
		// var_dump($result_first);
		// var_dump($result_last);
		// die;
		if($result_last && $result_first){
			$result = array('firstupdate'=>$result_first['lastupdate'],'lastupdate'=>$result_last['lastupdate']);
			json_return(true,$result);
		}else{
			json_return(false,"no data at all");
		}

	}

	/**
	 * save infomations from user feed back
	 * @return [type] [description]
	 */
	public function savefeedback(){
		$text = $this->input->post('text');
		if(!$text) {
			json_return(false,"no feedback at all!");
		}
		$data = array();

		$data['tid'] = $this->tid;
		$data['text'] = $text;
		$data['create_at'] = time();

		$table = "user_feedback";
		$this->load->model($table);
		$db = $this->$table->db;
		$where = array(
			'tid'=>$this->tid,
			'text'=>$text
			);
		
		$db->get_where($table,$where);

		if($db->affected_rows()){
			json_return(false,"save duplicate");
		}
		
		$db->insert($table,$data);
		if($db->affected_rows()){
			json_return(true,"save feedback sucessfully");
		}

		json_return(false,"save faid");

	}

	/**
	 * get user feed back
	 * @return [type] [description]
	 */
	public function getfeedback(){
		$table = "user_feedback";
		$this->load->model($table);
		$db = $this->$table->db;
		$where = array(
			'tid'=>$this->tid,
			);
		
		$result = $db->select("tid,text,create_at")->from($table)->where($where)->order_by("create_at desc")->get()->result_array();
		
		if($db->affected_rows()){
			$data = array(
				'success'=>true,
				'data'=>$result
				);
			echo json_encode($data);
			exit;
		}

		json_return(false,"no data");

	}

	/**
	 * [_checkTokenFromDb description]
	 * @return [type] [description]
	 */
	private function _checkTokenFromDb(){

		$this->load->model('user_token');

		return $this->user_token->checkToken($this->token);

	}

	/**	
	 * [_checkTokenFromPriveteApi description]
	 * @return [type] [description]
	 */
	private function _checkTokenFromPriveteApi(){

			$apiUrl = $this->config->item('token_check_api');

			$info = post($apiUrl,array('usertoken'=>$this->token));
			// var_dump($info);die;
			$info = json_decode($info);
			if(isset($info->success) && $info->success == true){
				
				$this->token 	= $info->token;
				$this->tid 		= $info->id;
				$this->email 	= $info->email;
				
				return true;
			}
			return false;
	}

	/**
	 * [_saveUser save user to local database]
	 * @return [void] [description]
	 */
	private function _saveUser(){
		$info = array('tid'=>$this->tid,'token'=>$this->token,'email'=>$this->email);
		// $token = $this->input->post('token');
		$this->load->model('user_token');

		return $this->user_token->saveUser($info);
	}


	// public function __call($name,$arg){
	// 	json_return(false,'no access allow');
	// }



}

?>